package com.donleo.security.service.impl;

import com.donleo.security.model.Permission;
import com.donleo.security.model.User;
import com.donleo.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;

/**
 * @author liangd
 * date 2020-12-08 19:10
 * code 自定义UserDetailsService
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;

    /**
     * 从数据库读取用户名认证
     * @param code 用户编号
     * @return UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String code) throws UsernameNotFoundException {
        User user= userService.getUserByCode(code);
        List<Permission> permissionList= userService.getPermissionsByUserCode(user.getCode());
        //获取用户拥有的权限
        HashSet<Permission> permissions = new HashSet<>(permissionList);
        user.setAuthorities(permissions);
        return user;
    }
}
